<script lang="ts">
    import {
        create_node,
        update_node_content,
        type ExDrawNodeInfo,
    } from "$lib/api/board/board_draw";
    import { get_user_session } from "$lib/api/user";
    import { request } from "$lib/utils/request";
    import { Modal, Tabs } from "@skeletonlabs/skeleton-svelte";
    import type { XYPosition } from "@xyflow/svelte";
    import { X } from "lucide-svelte";
    import mermaid from "mermaid";
    import type { Action } from "svelte/action";
    import { drawStore } from "../../store.svelte";
    import type { Store as ToastStore } from "@zag-js/toast";
    import { getContext } from "svelte";
    import { openUrl } from "@tauri-apps/plugin-opener";

    const toast: ToastStore = getContext("toast");

    interface ModalProps {
        nodeInfo?: ExDrawNodeInfo;
        width?: number;
        height?: number;
        position?: XYPosition;
        onClose: () => void;
    }
    let props: ModalProps = $props();

    let curTab = $state("edit" as "edit" | "preview");

    let mermaidContent = $state(
        props.nodeInfo?.content.DevelopMermaidContent?.content ?? "",
    );

    async function runRender(node: HTMLElement) {
        try {
            await mermaid.parse(mermaidContent);
        } catch (e) {
            console.log(e);
            node.innerHTML = `<span style="color:red;">错误的语法格式</span>`;
            return;
        }
        node.textContent = mermaidContent;
        node.removeAttribute("data-processed");
        await mermaid.run({
            nodes: [node],
            suppressErrors: true,
        });
    }

    const mermaidAction: Action = (node) => {
        mermaid.initialize({
            look: "handDrawn",
        });
        $effect(() => {
            if (curTab == "preview") {
                runRender(node);
            }
        });
    };

    async function createNode() {
        if (
            props.width == undefined ||
            props.height == undefined ||
            props.position == undefined
        ) {
            return;
        }
        try {
            await mermaid.parse(mermaidContent);
        } catch (e) {
            console.log(e);
            toast.create({
                title: "错误",
                description: "错误的mermaid格式！",
                type: "error",
            });
            return;
        }
        const sessionId = await get_user_session();
        await request(
            create_node({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id ?? "",
                draw_id: drawStore.drawId,
                x: props.position.x,
                y: props.position.y,
                w: props.width,
                h: props.height,
                content: {
                    DevelopMermaidContent: {
                        content: mermaidContent,
                    },
                },
                node_style: {
                    bg_color: "bg-surface-200",
                    border_width: "border-2",
                    border_color: "border-surface-300",
                    font_color: "text-surface-800",
                    layer: 0,
                },
            }),
        );
        props.onClose();
    }

    async function updateNode() {
        if (props.nodeInfo == undefined) {
            return;
        }
        try {
            await mermaid.parse(mermaidContent);
        } catch (e) {
            console.log(e);
            toast.create({
                title: "错误",
                description: "错误的mermaid格式！",
                type: "error",
            });
            return;
        }
        const sessionId = await get_user_session();
        await request(
            update_node_content({
                session_id: sessionId,
                board_id: drawStore.boardInfo?.board_id ?? "",
                draw_id: drawStore.drawId,
                node_id: props.nodeInfo.node_id,
                content: {
                    DevelopMermaidContent: {
                        content: mermaidContent,
                    },
                },
            }),
        );
        props.onClose();
    }
</script>

<Modal
    open={true}
    triggerBase="btn preset-tonal"
    contentBase="card bg-surface-200-800 p-4 space-y-4 shadow-xl shadow-surface-500 w-[800px]"
    backdropBase="backdrop-none"
    closeOnEscape={false}
    closeOnInteractOutside={false}
    onOpenChange={(ev) => {
        if (!ev.open) {
            props.onClose();
        }
    }}
>
    {#snippet content()}
        <header class="flex justify-between">
            <h4 class="h4">
                {props.nodeInfo == undefined
                    ? "创建Mermaid节点"
                    : "修改Mermaid节点"}
            </h4>
            <button
                type="button"
                class="btn preset-ghost-primary-500"
                onclick={() => props.onClose()}
            >
                <X />
            </button>
        </header>

        <main class="relative">
            <div class="absolute right-[20px] top-[10px]">
                <button class="button" onclick={()=>openUrl("https://mermaid.js.org/intro/")}>查看文档</button>
            </div>
            <Tabs
                value={curTab}
                onValueChange={(e) => (curTab = e.value as "edit" | "preview")}
            >
                {#snippet list()}
                    <Tabs.Control value="edit">编辑</Tabs.Control>
                    <Tabs.Control
                        value="preview"
                        disabled={mermaidContent.trim() == ""}
                        >预览</Tabs.Control
                    >
                {/snippet}
                {#snippet content()}
                    <Tabs.Panel value="edit">
                        <textarea
                            class="textarea bg-surface-100-900"
                            rows="10"
                            placeholder="请输入......"
                            bind:value={mermaidContent}
                        ></textarea>
                    </Tabs.Panel>
                    <Tabs.Panel value="preview">
                        <div class="max-h-[calc(100vh-400px)] overflow-y-auto">
                            <pre use:mermaidAction class="mermaid"></pre>
                        </div>
                    </Tabs.Panel>
                {/snippet}
            </Tabs>
        </main>
        <footer class="flex justify-end gap-4">
            <button
                type="button"
                class="btn preset-tonal"
                onclick={() => props.onClose()}>取消</button
            >
            <button
                type="button"
                class="btn preset-filled-primary-900-100"
                disabled={mermaidContent.trim() == ""}
                onclick={() => {
                    if (props.nodeInfo == undefined) {
                        createNode();
                    } else {
                        updateNode();
                    }
                }}
            >
                确定
            </button>
        </footer>
    {/snippet}
</Modal>
